package com.xucy.springboot.common;

/**
 * @Author xucy
 * @Date 2019-03-26 20:08
 * @Description 我的简单循环队列（可以在队列中数据都弹出后，继续向里面插入数据）
 **/

public class MyCircleQuequ {

    //队列底层数组
    private long[] arr;

    private int front;

    private int end;

    private int elements;

    MyCircleQuequ() {
        arr = new long[10];
        front = 0;
        end = -1;
        elements = 0;
    }

    MyCircleQuequ(int size) {
        arr = new long[size];
        front = 0;
        end = -1;
        elements = 0;
    }

    /**
     * 添加数据
     *
     * @param
     * @return
     * @Author xucy
     * @Date 20:12 2019-03-26
     */
    public void insert(long value) {
        if (elements == arr.length) {
            throw new ArrayIndexOutOfBoundsException();
        }
        if (end == arr.length - 1) {
            end = -1;
        }
        elements++;
        arr[++end] = value;
    }

    /**
     * 查看队头数据
     *
     * @param
     * @return
     * @Author xucy
     * @Date 20:15 2019-03-26
     */
    public long peek() {
        return arr[front];
    }

    /**
     * 移除数据
     *
     * @param
     * @return
     * @Author xucy
     * @Date 20:18 2019-03-26
     */
    public long pop() {
        long value = arr[front++];
        if (front == arr.length) {
            front = 0;
        }
        elements--;
        return value;
    }

    /**
     * 判断是否为空
     *
     * @param
     * @return
     * @Author xucy
     * @Date 20:18 2019-03-26
     */
    public boolean isEmpty() {
        return elements == 0;
    }

    /**
     * 判断是否已满
     *
     * @param
     * @return
     * @Author xucy
     * @Date 20:18 2019-03-26
     */
    public boolean isFull() {
        return elements == arr.length;
    }

    public static void main(String[] args) {
        MyCircleQuequ myCQuequ = new MyCircleQuequ(4);
        myCQuequ.insert(22);
        myCQuequ.insert(14);
        myCQuequ.insert(11);
        myCQuequ.insert(16);

        System.out.println(myCQuequ.peek());
        while (!myCQuequ.isEmpty()) {
            System.out.println(myCQuequ.pop() + " ");
        }

        myCQuequ.insert(22);
        myCQuequ.insert(14);
        myCQuequ.insert(11);
        myCQuequ.insert(16);

        System.out.println(myCQuequ.peek());
        while (!myCQuequ.isEmpty()) {
            System.out.println(myCQuequ.pop() + " ");
        }
    }
}
